package com.anntly.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @Auther: 张文
 * @Date: 2020/5/5 15:36
 * @Description:
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    // 就绪后就发送消息
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 发送一个student对象到服务器
        StudentPOJO.Student student = StudentPOJO.Student.newBuilder().setId(1).setName("小红").build();
        ctx.writeAndFlush(student);
        //ctx.writeAndFlush(Unpooled.copiedBuffer("hello server", CharsetUtil.UTF_8));
    }

    // 服务服务端返回的消息
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("server ctx:"+ctx);
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("msg:"+buf.toString(CharsetUtil.UTF_8));
        System.out.println("server address:"+ctx.channel().remoteAddress());
    }

    // 处理异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
